package cn.zmwh.portal.modules.miniapp.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.json.JSONUtil;
import cn.zmwh.common.core.api.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信小程序用户接口
 */
@Slf4j
@RestController
@Api(tags = "小程序相关")
public class WxMaUserController {

    @Autowired
    private WxMaService wxMaService;

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @GetMapping("/wx/user/{appid}/phone")
    @ApiOperation(value = "获取手机号接口")
    public Result phone(@PathVariable String appid, String code) throws WxErrorException {
        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(code);
        log.info(JSONUtil.toJsonStr(phoneNoInfo));
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        String purePhoneNumber = phoneNoInfo.getPurePhoneNumber();
        if (phoneNumber.length() != 11) {
            phoneNumber = purePhoneNumber;
        }
        return Result.ok(phoneNumber);
    }

}
